<template>
  <div class="map-page">
    <div class="head">
      <div class="search-box">
        <van-search
          v-model="search_key"
          clearable
          show-action
          placeholder="请输入搜索关键词"
          @search="autoCompleteSearch"
          @input="onKeyInput"
          @clear="search_key = ''"
        >
          <template #label>
            <span @click.stop.prevent="handshowCitylist">
              {{ city ? city : "" }}
              <van-icon name="arrow-down" />
            </span>
          </template>
          <template #action>
            <div @click="autoCompleteSearch">搜索</div>
          </template>
        </van-search>
      </div>
      <!--地图-->
      <div class="mapbox">
        <div id="container" class="map"></div>
        <div class="sign"></div>
      </div>
    </div>

    <div class="address-list">
      <div v-for="(item, index) in addressList" :key="index" class="address-item" @click="onSelectAddress(item)">
        <div class="mb-5">
          <van-icon class="c-999 mr-5" name="location" />
          <span class="name">{{ item.name }}</span>
        </div>
        <div class="text">
          {{ item.address }}
        </div>
        <!-- <van-button size="mini" type="danger" class="select" @click="onSelectAddress(item)">选择</van-button> -->
      </div>

      <van-empty class="ta-c" v-if="addressList.length === 0" description="暂无地址信息，请尝试拖动地图选址" />
    </div>

    <van-action-sheet v-model:show="iscityShow" title="配送城市" style="height: 50%" get-container="#app" :close-on-click-overlay="false" :closeable="false">
      <van-search v-model="citySearch" placeholder="请输入搜索关键词" @update:model-value="selectCityList" />
      <van-radio-group v-model="city" class="city-list">
        <van-radio
          v-for="item in selfcity"
          :key="item.id"
          class="city-item"
          :name="item.deptName"
          :value="item.id"
          checked-color="#ff0000"
          @click="onSelectCity(item)"
        >{{ item.deptName }}</van-radio>
      </van-radio-group>
    </van-action-sheet>
  </div>
</template>

<script>
import { debounce } from '@/utils'
import {
  getisRange, // 判断范围
  getSelfDelivery // 获取城市列表
} from '@/api/common'
import { Toast } from 'vant'
import { inputTip } from '@/utils/map'

export default {
  name: 'Map',
  data() {
    return {
      city: '',
      search_key: '',
      selfcity: [],
      iscityShow: true,
      citySearch: '',
      addressList: []
    }
  },
  created() {
    this.keySearchDebounce = debounce(this.autoCompleteSearch, 500)
  },
  activated() {
    this.iscityShow = true
  },
  mounted() {
    getSelfDelivery().then((res) => {
      this.selfcity = res.data || []
      this.originCityList = this.selfcity
    }).then(() => {
      // if (localStorage.getItem("city")) {
      //   this.city = localStorage.getItem("city");
      //   this.deptId = localStorage.getItem("deptId");
      // }
    })
    // this.getCityInfo().then((result) => {
      // if (result && result.city && result.bounds) {
      //   this.city = result.city
      // }
      this.initMap().then(() => {
        this.initControl(this._map)
      })
      this.autoCompleteSearch()
      
    // })
  },
  methods: {
    // 初始化地图
    initMap(center) {
      return new Promise((resolve) => {
        // 初始化地图
        var map = (this._map = new AMap.Map('container', {
          zoom: 16, // 缩放级别
          center: center || this.center, // 设置地图中心点
          resizeEnable: true, // 地图初始化加载定位到当前城市
          zoomEnable: false
        }))

        // 获取初始中心点并赋值
        var currentCenter = map.getCenter() // 此方法是获取当前地图的中心点
        this.center = [currentCenter.lng, currentCenter.lat] // 将获取到的中心点的纬度经度赋值给data的center
        // 创建标记
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(currentCenter.lng, currentCenter.lat) // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
        })
        map.on('mapmove', () => {
          const currentCenter = map.getCenter()
          this.marker.setPosition([currentCenter.lng, currentCenter.lat])
        }) //更新标记
        map.on('dragend', () => {
          this.centerSearch()
        }) //更新数据
        // 将创建的点标记添加到已有的地图实例：
        map.add(this.marker)
        resolve()
      })
    },

    // 拖拽地图选址
    centerSearch() {
      Toast.loading('加载中...')
      AMap.plugin(['AMap.PlaceSearch'], () => {
        // 构造地点查询类
        this._placeSearchObj = new AMap.PlaceSearch({
          type: '购物服务|体育休闲服务|医疗保健服务|住宿服务|商务住宅|科教文化服务', // 兴趣点类别
          pageSize: 30, // 单页显示结果条数
          citylimit: true,
          extensions: 'all',
          pageIndex: 1, // 页码
          city: '', // 兴趣点城市
          autoFitView: false // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        })
        //根据地图中心点查附近地点
        const currentCenter = this._map.getCenter()
        this._placeSearchObj.searchNearBy('', [currentCenter.lng, currentCenter.lat], 200, (status, result) => {
          Toast.clear()
          if (status == 'complete') {
            this.addressList = result.poiList.pois //将查询到的地点赋值
            if (this.addressList && this.addressList.length) {
              this.addressList = this.addressList.filter(item => item.location).map(item => {
                return {
                  name: item.name,
                  cityname: item.cityname || this.city,
                  address: item.pname + item.cityname + item.name + item.address,
                  lng: item.location.lng,
                  lat: item.location.lat,
                  location: [item.location.lng, item.location.lat]
                }
              })
            }
          } else {
            this.addressList = []
          }
        })
      })
    },

    selectCityList(value) {
      if (value) {
        this.selfcity = this.originCityList.filter(item => item.deptName.includes(value))
      } else {
        this.selfcity = this.originCityList || []
      }
    },
    autoCompleteSearch() {
      Toast.loading('加载中...')
      // 关键字查询
      inputTip({
        city: this.city,
        keyword: this.search_key || this.city
      }).then(addressList => {
        Toast.clear()
        if (addressList && addressList.length) {
          this.addressList = (addressList || []).filter(item => item.location).map(item => {
            return {
              name: item.name,
              cityname: this.city,
              address: item.district + item.address,
              lng: item.location.lng,
              lat: item.location.lat,
              location: [item.location.lng, item.location.lat]
            }
          })
          const firstAdd = this.addressList[0]
          firstAdd && this.setMapCenter(firstAdd.location)
        } else {
          this.addressList = []
        }
      })
    },

    onSelectCity(item) {
      // 配送范围
      this.deptId = item.id
      this.city = item.deptName
      localStorage.setItem('deptId', item.id)
      localStorage.setItem('city', item.deptName)
      this.iscityShow = false
      this.autoCompleteSearch()
    },
    handshowCitylist() {
      this.iscityShow = true
    },
    onKeyInput() {
      this.keySearchDebounce()
    },
    async onSelectAddress(item) {
      const params = {}
      this.marker.setPosition(item.location)
      this._map.setCenter(item.location)
      params['cityName'] = this.city
      params['deptId'] = this.deptId
      params['location'] = item.location.join(',')
      getisRange(params).then((res) => {
        console.log(3)
        if (res.code !== 200) {
          Toast.fail('该地址不在配送范围')
        } else {
          localStorage.setItem('selectAddress', JSON.stringify({
            ...item,
          }))
          this.$router.push({
            path: '/home',
            query: {
              ...this.$route.query,
              clearCode: undefined,
              showGuide: undefined,
              setIsDance: true,
            }
          })
        }
      })
    },
    onLocation(e) {
      const sendObj = {}
      const str = `${e.location.lng},${e.location.lat}`
      sendObj['cityName'] = this.city
      sendObj['deptId'] = this.deptId
      sendObj['location'] = str
      this.setMapCenter([e.location.lng, e.location.lat])
      this._map.setCenter([e.location.lg, e.location.lat])
      getisRange(sendObj).then((res) => {
        if (res.code !== 200) {
          Toast.fail('该地址不在配送范围')
        }
      })
    },
    setMapCenter(center) {
      this.marker.setPosition(center)
      this._map.setCenter(center)
    },
    // 获取用户所在城市信息
    getCityInfo() {
      return new Promise(resolve => {
        // 实例化城市查询类
        AMap.plugin(['AMap.CitySearch'], () => {
          var citysearch = new AMap.CitySearch()
          // 自动获取用户IP，返回当前城市
          citysearch.getLocalCity((status, result) => {
            if (status === 'complete' && result.info === 'OK') {
            } else {
              Toast.fail(result.info)
            }
            resolve(result)
          })
        })
      })
    },
    initControl(map) {
      AMap.plugin('AMap.Geolocation,AMap.Scale', () => {
        const scale = new AMap.Scale()
        map.addControl(scale)
        var geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：5s
          position:'RB',    //定位按钮的停靠位置
          offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
          zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
        });
        map.addControl(geolocation);
        geolocation.on('complete', () => {
          this.centerSearch({city: ''})
        });//返回定位信息
        geolocation.getCurrentPosition(function(status){
          if(status=='complete'){
          }else{
          }
        });
      });
    }
  }
}
</script>

<style lang="less" scoped>
.map-page {
  height: 100vh;
  background: #f8f8f8;
  .head {
    position: sticky;
    top: 0px;
    z-index: 10;
    height: 300px;
  }
  .mapbox {
    width: 100%;
    height: 240px;
    background: #eceeee;

    .map {
      width: 100%;
      height: 240px;
    }
  }
}
.address-list {
  height: calc(100% - 300px);
  overflow: auto;
  .address-item {
    padding: 12px;
    padding-right: 50px;
    background-color: #fff;
    margin-top: 10px;
    font-size: 14px;
    position: relative;
    .name {
      font-weight: bold;
    }
    .text {
      color: #999;
      padding-left: 16px;
    }
    .select {
      position: absolute;
      top: 40%;
      right: 10px;
    }
  }
}
.city-list {
  padding: 0 12px;
  font-size: 14px;
  .city-item {
    line-height: 32px;
    height: 32px;
  }
}
</style>
